//
//  UIButton+imageTitleLayout.m
//
//
//  Created by 韩保玉 on 15/6/28.
//  Copyright (c) 2015年 韩保玉. All rights reserved.
//

#import "UIButton+MJUI.h"

@implementation UIButton (IB)

@dynamic mj_titleColorName;
- (void)setMj_titleColorName:(NSString *)mj_titleColorName {
    [self setTitleColor:[UIColor mj_colorName:mj_titleColorName] forState:0];
}
@dynamic mj_fontStyleName;
- (void)setMj_fontStyleName:(NSString *)mj_fontStyleName {
    self.titleLabel.font = [UIFont fontWithName:mj_fontStyleName size:self.titleLabel.font.pointSize];
}
@dynamic mj_boldSize;
- (void)setMj_boldSize:(CGFloat)mj_boldSize {
    self.titleLabel.font = [UIFont boldSystemFontOfSize:mj_boldSize];
}
@dynamic mj_systemSize;
- (void)setMj_systemSize:(CGFloat)mj_systemSize {
self.titleLabel.font = [UIFont systemFontOfSize:mj_systemSize];
}
@dynamic mj_enabled;
- (void)setMj_enabled:(BOOL)mj_enabled {
    self.enabled = mj_enabled;
    if(mj_enabled){
        self.alpha = 1;
    }else{
        self.alpha = 0.5;
    }
}
@end

/// 语言
@implementation UIButton (Language)

@dynamic mj_localizable;
- (void)setMj_localizable:(NSString *)mj_localizable {
    
    MJWeakSelf
    [RACObserve(LanguageHelper.shared, language) subscribeNext:^(NSString *language) {
        [weakSelf setTitle:MJUILocalizedString(mj_localizable) forState:0];
    }];

}
@end


@implementation UIButton (MJUI)

- (void)mj_layoutButtonWithEdgeInsetsStyle:(ButtonEdgeInsetsStyle)style imageTitlespace:(CGFloat)space {
    CGFloat imageViewWidth = CGRectGetWidth(self.imageView.frame);
    CGFloat labelWidth = CGRectGetWidth(self.titleLabel.frame);
    
    if (labelWidth == 0) {
        CGSize titleSize = [self.titleLabel.text sizeWithAttributes:@{NSFontAttributeName:self.titleLabel.font}];
        labelWidth  = titleSize.width;
    }
    
    CGFloat imageInsetsTop = 0.0f;
    CGFloat imageInsetsLeft = 0.0f;
    CGFloat imageInsetsBottom = 0.0f;
    CGFloat imageInsetsRight = 0.0f;
    
    CGFloat titleInsetsTop = 0.0f;
    CGFloat titleInsetsLeft = 0.0f;
    CGFloat titleInsetsBottom = 0.0f;
    CGFloat titleInsetsRight = 0.0f;
    
    switch (style) {
        case ButtonEdgeInsetsStyleImageRight:
        {
            space = space * 0.5;

            imageInsetsLeft = labelWidth + space;
            imageInsetsRight = -imageInsetsLeft;
            
            titleInsetsLeft = - (imageViewWidth + space);
            titleInsetsRight = -titleInsetsLeft;
        }
            break;
            
        case ButtonEdgeInsetsStyleImageLeft:
        {
            space = space * 0.5;

            imageInsetsLeft = -space;
            imageInsetsRight = -imageInsetsLeft;
            
            titleInsetsLeft = space;
            titleInsetsRight = -titleInsetsLeft;
        }
            break;
        case ButtonEdgeInsetsStyleImageBottom:
        {
            CGFloat imageHeight = CGRectGetHeight(self.imageView.frame);
            CGFloat labelHeight = CGRectGetHeight(self.titleLabel.frame);
            CGFloat buttonHeight = CGRectGetHeight(self.frame);
            CGFloat boundsCentery = (imageHeight + space + labelHeight) * 0.5;
            
            CGFloat centerX_button = CGRectGetMidX(self.bounds); // bounds
            CGFloat centerX_titleLabel = CGRectGetMidX(self.titleLabel.frame);
            CGFloat centerX_image = CGRectGetMidX(self.imageView.frame);
            
            CGFloat imageBottomY = CGRectGetMaxY(self.imageView.frame);
            CGFloat titleTopY = CGRectGetMinY(self.titleLabel.frame);
            
            imageInsetsTop = buttonHeight - (buttonHeight * 0.5 - boundsCentery) - imageBottomY;
            imageInsetsLeft = centerX_button - centerX_image;
            imageInsetsRight = - imageInsetsLeft;
            imageInsetsBottom = - imageInsetsTop;
            
            titleInsetsTop = (buttonHeight * 0.5 - boundsCentery) - titleTopY;
            titleInsetsLeft = -(centerX_titleLabel - centerX_button);
            titleInsetsRight = - titleInsetsLeft;
            titleInsetsBottom = - titleInsetsTop;
            
        }
            break;
            case ButtonEdgeInsetsStyleImageTop:
        {
            CGFloat imageHeight = CGRectGetHeight(self.imageView.frame);
            CGFloat labelHeight = CGRectGetHeight(self.titleLabel.frame);
            CGFloat buttonHeight = CGRectGetHeight(self.frame);
            CGFloat boundsCentery = (imageHeight + space + labelHeight) * 0.5;
            
            CGFloat centerX_button = CGRectGetMidX(self.bounds); // bounds
            CGFloat centerX_titleLabel = CGRectGetMidX(self.titleLabel.frame);
            CGFloat centerX_image = CGRectGetMidX(self.imageView.frame);
            
            CGFloat imageTopY = CGRectGetMinY(self.imageView.frame);
            CGFloat titleBottom = CGRectGetMaxY(self.titleLabel.frame);
            
            imageInsetsTop = (buttonHeight * 0.5 - boundsCentery) - imageTopY;
            imageInsetsLeft = centerX_button - centerX_image;
            imageInsetsRight = - imageInsetsLeft;
            imageInsetsBottom = - imageInsetsTop;
            
            titleInsetsTop = buttonHeight - (buttonHeight * 0.5 - boundsCentery) - titleBottom;
            titleInsetsLeft = -(centerX_titleLabel - centerX_button);
            titleInsetsRight = - titleInsetsLeft;
            titleInsetsBottom = - titleInsetsTop;
        }
            break;
            
        default:
            break;
    }
    
    self.imageEdgeInsets = UIEdgeInsetsMake(imageInsetsTop, imageInsetsLeft, imageInsetsBottom, imageInsetsRight);
    self.titleEdgeInsets = UIEdgeInsetsMake(titleInsetsTop, titleInsetsLeft, titleInsetsBottom, titleInsetsRight);
}

static char ActionTag;

- (void)mj_addAction:(ButtonBlock)block
{
    objc_setAssociatedObject(self, &ActionTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)mj_addAction:(ButtonBlock)block forControlEvents:(UIControlEvents)controlEvents
{
    objc_setAssociatedObject(self, &ActionTag, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(action:) forControlEvents:controlEvents];
}

- (void)action:(id)sender
{
    ButtonBlock blockAction = (ButtonBlock)objc_getAssociatedObject(self, &ActionTag);
    if (blockAction)
    {
        blockAction(self);
    }
}

- (void)mj_paragraphStyleWithArrString:(NSArray *)arrString title:(NSString *)title font:(UIFont * _Nullable)font color:(UIColor * _Nullable)color{
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    NSDictionary *ats = @{NSParagraphStyleAttributeName : paragraphStyle};
    NSMutableAttributedString *paragraphString = [[NSMutableAttributedString alloc] initWithString:title attributes:ats];
    for(NSString *string in arrString)
    {
        if(!string){
            return;
        }
        if(font){
            [paragraphString addAttribute:NSFontAttributeName
                                    value:font
                                    range:[title rangeOfString:string]];
        }
        if(color){
            [paragraphString addAttribute:NSForegroundColorAttributeName
                                    value:color
                                    range:[title rangeOfString:string]];
        }
        
    }
    
    [self setAttributedTitle:paragraphString forState:UIControlStateNormal];
}

@end


@implementation UIButton (Countdown)

-(void)mj_createTimerWithDuration:(NSInteger)duration{
    
    [self mj_createTimerWithDuration:duration normalTitle:MJUILocalizedString(@"Resend code") selectTitle:@"" index:0];
}

-(void)mj_createTimerWithDuration:(NSInteger)duration normalTitle:(NSString *)normalTitle selectTitle:(NSString *)selectTitle index:(NSInteger)index{
    
    self.userInteractionEnabled = NO;
    
    //设置倒计时时间
    //通过检验发现，方法调用后，timeout会先自动-1，所以如果从15秒开始倒计时timeout应该写16
    //__block 如果修饰指针时，指针相当于弱引用，指针对指向的对象不产生引用计数的影响
    __block NSInteger timeout = duration;
    
    //获取全局队列
    dispatch_queue_t global = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //创建一个定时器，并将定时器的任务交给全局队列执行(并行，不会造成主线程阻塞)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, global);
    
    // 设置触发的间隔时间
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    //1.0 * NSEC_PER_SEC  代表设置定时器触发的时间间隔为1s
    //0 * NSEC_PER_SEC    代表时间允许的误差是 0s
    
    //block内部 如果对当前对象的强引用属性修改 应该使用__weak typeof(self)weakSelf 修饰  避免循环调用
    __weak typeof(self)weakSelf = self;
    //设置定时器的触发事件
    dispatch_source_set_event_handler(timer, ^{
        //倒计时  刷新button上的title ，当倒计时时间为0时，结束倒计时
        //1. 每调用一次 时间-1s
        timeout --;
        //2.对timeout进行判断时间是停止倒计时，还是修改button的title
        if (timeout <= 0) {            //停止倒计时，button打开交互，背景颜色还原，title还原
            //关闭定时器
            dispatch_source_cancel(timer);
            //button上的相关设置
            //注意: button是属于UI，在iOS中多线程处理时，UI控件的操作必须是交给主线程(主队列)
            //在主线程中对button进行修改操作
            dispatch_async(dispatch_get_main_queue(), ^{
                
                weakSelf.userInteractionEnabled = YES;
                [weakSelf mj_paragraphStyleWithArrString:@[normalTitle] title:normalTitle font:nil color:UIColor.mj_appColor];
            });
        }else {
            //处于正在倒计时，在主线程中刷新button上的title，时间-1秒
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * title = [NSString stringWithFormat:@"%@ %lds",MJUILocalizedString(@"Send in"),timeout];
                [weakSelf mj_paragraphStyleWithArrString:@[MJUILocalizedString(@"Send in")] title:title font:nil color:UIColor.mj_lightGrayColor];
            });
        }
    });
    
    dispatch_resume(timer);
}

@end
